package handler

import (
	"chat_oa/api/request"
	"chat_oa/consts"
	"chat_oa/internal/dao"
	"chat_oa/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
)

func Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile, Password: req.Password}, &user)
	if user.Id == 0 {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "账号或密码错误，请重新输入",
			"data":    nil,
		})
		return
	}
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 3600*24*7,
		},
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "生成token失败",
			"data":    nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "生成token成功",
		"data":    token,
	})
}
